package top.whysu.edevice.filter;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.DefaultSessionKey;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import top.whysu.edevice.constant.CodeConstant;
import top.whysu.edevice.constant.Constant;
import top.whysu.edevice.dto.generate.HeaderDTO;
import top.whysu.edevice.dto.generate.ResponseDTO;
import top.whysu.edevice.dto.generate.ResultDTO;
import top.whysu.edevice.dto.websocket.SessionDTO;
import top.whysu.edevice.utils.ShiroUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;
import java.util.*;

public class KickoutSessionControlFilter extends AccessControlFilter {
    private static final Logger LOGGER = LoggerFactory.getLogger(KickoutSessionControlFilter.class);

    @Autowired
    private SimpMessagingTemplate messagingTemplate;
    /**
     * 踢出后到的地址
     */
    private String kickoutUrl;
    /**
     * 踢出之前登录的/之后登录的用户 默认踢出之前登录的用户
     */
    private boolean kickoutAfter = false;
    /**
     * 同一个帐号最大会话数 默认1
     */
    private int maxSession = 1;

    private SessionManager sessionManager;
    private Cache<String, Deque<Serializable>> cache;

    public void setKickoutUrl(String kickoutUrl) {
        this.kickoutUrl = kickoutUrl;
    }

    public void setKickoutAfter(boolean kickoutAfter) {
        this.kickoutAfter = kickoutAfter;
    }

    public void setMaxSession(int maxSession) {
        this.maxSession = maxSession;
    }

    public void setSessionManager(SessionManager sessionManager) {
        this.sessionManager = sessionManager;
    }

    /**
     * 设置Cache的key的前缀
     */
    public void setCacheManager(CacheManager cacheManager) {
        this.cache = cacheManager.getCache("shiro-kickout-session");
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        Subject subject = getSubject(request, response);
        if (!subject.isAuthenticated() && !subject.isRemembered()) {
            //如果没有登录，直接进行之后的流程
            return true;
        }

        Session session = subject.getSession();
        String username = (String) subject.getPrincipal();
        Serializable sessionId = session.getId();
        //读取缓存 没有就存入
        Deque<Serializable> deque = cache.get(username);

        if (deque == null) {
            deque = new LinkedList<Serializable>();
            cache.put(username, deque);
        }

        //如果队列里没有此sessionId，且用户没有被踢出；放入队列
        if (!deque.contains(sessionId) && session.getAttribute("kickout") == null) {
            //将sessionId存入队列
            deque.push(sessionId);
        }

        //如果队列里的sessionId数超出最大会话数，开始踢人
        while (deque.size() > maxSession) {
            Serializable kickoutSessionId = null;
            //如果踢出后者
            if (kickoutAfter) {
                kickoutSessionId = deque.removeFirst();
            } else { //否则踢出前者
                kickoutSessionId = deque.removeLast();
            }
            try {
                //获取被踢出的sessionId的session对象
                Session kickoutSession = sessionManager.getSession(new DefaultSessionKey(kickoutSessionId));
                if (kickoutSession != null) {
                    //设置会话的kickout属性表示踢出了
                    kickoutSession.setAttribute("kickout", true);
                }
            } catch (Exception e) {//ignore exception
            }
        }

        //如果被踢出了，直接退出，重定向到踢出后的地址
        if (session.getAttribute("kickout") != null) {
            //会话被踢出了
            try {
                //退出登录
                subject.logout();
            } catch (Exception e) { //ignore
            }
            Map<String, Object> result = new HashMap<String, Object>();
            //判断是不是Ajax请求
            if (ShiroUtils.isAjax(request)) {
                authFailResponse(response, "您已经被踢出，请重新登录！");
            } else {
                WebUtils.getSavedRequest(request);
                //再重定向到登录页面
                WebUtils.issueRedirect(request, response, kickoutUrl);
            }
            return false;
        }
        return true;
    }

    /***
     * 失败应答
     */
    private void authFailResponse(ServletResponse response, String msg) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        PrintWriter pw = response.getWriter();
        final ResponseDTO responseDTO = new ResponseDTO<>();
        HeaderDTO headerDTO = new HeaderDTO();
        headerDTO.setDateTime(String.valueOf(Calendar.getInstance().getTimeInMillis()));
        responseDTO.setHeader(headerDTO);
        responseDTO.setResult(new ResultDTO(CodeConstant.Http.AUTHORIZATION_FAIL, msg));
        pw.print(JSONObject.toJSONString(responseDTO));
        pw.flush();
        pw.close();
    }

    /**
     * 发送websocket给前端，强制该用户下线
     */
    public void kickByUserName(String username) {
        try {
            if (StringUtils.isNotBlank(username)) {
                Deque<Serializable> deque = cache.get(username);
                if (deque != null) {
                    LOGGER.info("强制该用户下线：{}", username);
                    SessionDTO sessionDTO = new SessionDTO(Constant.AccountAlarm.KICKOUT_MESSAGE);
                    sessionDTO.setMethod(Constant.WebSocket.ALARM_ACCOUNT_KICKOUT);
                    sessionDTO.setJsessionid(deque.getLast().toString());
                    messagingTemplate.convertAndSend(Constant.WebSocket.DESTINATION, sessionDTO);
                }
            }
        } catch (Exception e) {
            LOGGER.error("踢出用户名发生异常,username:{}", username, e);
        }
    }
}

